package com.u.finance.pay.service.impl;

import com.u.finance.pay.entity.PayRecord;
import com.u.finance.pay.mapper.PayRecordMapper;
import com.u.finance.pay.service.IPayRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import jakarta.annotation.Resource;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author Alex Wu
 * @since 2025-03-31
 */
@Service
public class PayRecordServiceImpl extends ServiceImpl<PayRecordMapper, PayRecord> implements IPayRecordService {


    @Resource
    private RocketMQTemplate rocketMQTemplate;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean transferCount(String payoutAccount, BigDecimal amount, Integer payType) {
        // 同步发起转账业务
        System.out.println("调起第三方转账业务, fetch pay account");
        if(aliPay()){
            // 支付成功
            // 记录支付记录
            PayRecord payRecord = new PayRecord();
            payRecord.setAmount(amount);
            payRecord.setPayoutAccount(payoutAccount);
            payRecord.setIsPay(true);
            payRecord.setInAccount("u-pay");
            this.save(payRecord);
            return true;
        }
        return false;
    }

    @Override
    public boolean repay(String payoutAccount, BigDecimal amount, Integer payType) {
        // 同步发起转账业务
        boolean isSuccess = this.transferCount(payoutAccount, amount, payType);
        if(isSuccess){
            rocketMQTemplate.convertAndSend("pay-topic", "pay-success");
        }
        return isSuccess;
    }

    private Boolean aliPay() {
        System.out.println("支付宝支付");
        return true;
    }
}
